package com.findu.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.ciaapp.sdk.CIAService;
import cn.ciaapp.sdk.VerificationListener;

import com.easemob.EMError;
import com.easemob.chat.EMChatManager;
import com.easemob.exceptions.EaseMobException;
import com.example.findu.R;
import com.example.findu.R.drawable;
 

/**
 * @Title: RegisterActivity.java
 * @Package com.findu.activity
 * @Description: TODO(用一句话描述该文件做什么)
 * @author ggj
 * @date 2015-10-30 下午4:34:00
 * @version V1.0
 */
public class RegisterActivity extends BaseActivity  {

	// Content View Elements

	private ImageView mRegister_backImage;
	private TextView mRegister_textView;
	private EditText mRegister_edt_name;
	private EditText mRegister_edt_pwd;
	private EditText mRegister_edt_regpwd;
	private CheckBox mRegister_ck_agreen;
	private Button mRegister_button;
	/**
	 * 对话框
	 */
	private  ProgressDialog progressDialog;
     /**
      * 输入框的值
      */
	private String username;
	private String pwd;
	 

	// End Of Content View Elements

	private void bindViews() {

		mRegister_backImage = (ImageView) findViewById(R.id.register_backImage);
		mRegister_textView = (TextView) findViewById(R.id.register_textView);
		mRegister_edt_name = (EditText) findViewById(R.id.register_edt_name);
		mRegister_edt_pwd = (EditText) findViewById(R.id.register_edt_pwd);
		mRegister_edt_regpwd = (EditText) findViewById(R.id.register_edt_regpwd);
		mRegister_ck_agreen = (CheckBox) findViewById(R.id.register_ck_agreen);
		mRegister_button = (Button) findViewById(R.id.register_button);
		progressDialog=new ProgressDialog(this);
		 
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// 加载页面
		setContentView(R.layout.register);
		// 初始控件
		bindViews();
		
		mRegister_backImage.setOnClickListener(this);
		// 单选框
		mRegister_ck_agreen.setOnClickListener(this);
		// 注册提交
		mRegister_button.setOnClickListener(this);
		super.onCreate(savedInstanceState);
	}

	/**
	 * 返回到登录页面
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		// 根据id判断不同的按钮做不同的事情
		case R.id.register_backImage:
			// 跳转到登录页面
			LoginActivity.start(this);
			break;
		case R.id.register_button:
			// 提交到后台
			//Toast.makeText(RegisterActivity.this, "http========提交到后台", 0).show();
					
			register();
			break;
		case R.id.register_ck_agreen:
			// 判断按钮是否被选中
			check(mRegister_ck_agreen);
			break;
		}
	}

	public void check(CheckBox mRegister_ck_agreen) {
		if (!mRegister_ck_agreen.isChecked()) {
			Toast.makeText(RegisterActivity.this, "没选择%%%", 0).show();
			// 调用方法:改变按钮的背景颜色 & 事件取消
			// mRegister_button.setBackgroundColor(121212);
			mRegister_button.setBackgroundColor(drawable.bottom_text_color3);
			mRegister_button.setClickable(false);
		} else {
			// 恢复注册事件
			mRegister_button.setClickable(true);
	 
			mRegister_button.setBackgroundColor(drawable.bottom_text_color2);
		}

	}

	public static void start(Context context) {
		Intent intent = new Intent(context, RegisterActivity.class);
		context.startActivity(intent);
	}
	/**
	 * 环信注册
	 * 
	 * @param view
	 */
	//public void register(View view) {
		public void register() {
// 	final String username = mRegister_edt_name.getText().toString().trim();
// 		final String pwd = mRegister_edt_pwd.getText().toString().trim();
 		 username = mRegister_edt_name.getText().toString().trim();
 		 pwd = mRegister_edt_pwd.getText().toString().trim();
		String confirm_pwd = mRegister_edt_regpwd.getText().toString().trim();
		//用户名
		if (TextUtils.isEmpty(username)) {
			Toast.makeText(this, getResources().getString(R.string.User_name_cannot_be_empty), Toast.LENGTH_SHORT).show();
			mRegister_edt_name.requestFocus();
			return;
		//密码
		} else if (TextUtils.isEmpty(pwd)) {
			Toast.makeText(this, getResources().getString(R.string.Password_cannot_be_empty), Toast.LENGTH_SHORT).show();
			mRegister_edt_pwd.requestFocus();
			return;
		//再次输入秘密
		} else if (TextUtils.isEmpty(confirm_pwd)) {
			Toast.makeText(this, getResources().getString(R.string.Confirm_password_cannot_be_empty), Toast.LENGTH_SHORT).show();
			mRegister_edt_regpwd.requestFocus();
			return;
			//两次密码不一样
		} else if (!pwd.equals(confirm_pwd)) {
			Toast.makeText(this, getResources().getString(R.string.Two_input_password), Toast.LENGTH_SHORT).show();
			return;
		}

		if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(pwd)) {
			//final ProgressDialog pd = new ProgressDialog(this);
			progressDialog.setMessage(getResources().getString(R.string.Is_the_registered));
			progressDialog.show();
			
			//CIA验证手机
			verification(username);
			 
			    
			   
			 /*new Thread(new Runnable() {
				public void run() {
					try {
					   
						// 调用sdk注册方法
						EMChatManager.getInstance().createAccountOnServer(username, pwd);
						runOnUiThread(new Runnable() {
							public void run() {
								if (!RegisterActivity.this.isFinishing())
									pd.dismiss();
								// TODO  保存用户名,注册成功后跳转到登录页面 
						  	    //DemoHelper.getInstance().setCurrentUserName(username);
							    // PreferenceManager.getInstance().setCurrentUserName(username);
								//Toast.makeText(getApplicationContext(), getResources().getString(R.string.Registered_successfully), 0).show();
								 Toast.makeText(RegisterActivity.this, getResources().getString(R.string.Registered_successfully), 0).show();
								back();
								finish();
							}
						});
					} catch (final EaseMobException e) {
						runOnUiThread(new Runnable() {
							public void run() {
								if (!RegisterActivity.this.isFinishing())
									pd.dismiss();
								int errorCode=e.getErrorCode();
								if(errorCode==EMError.NONETWORK_ERROR){
									Toast.makeText(getApplicationContext(), getResources().getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
								}else if(errorCode == EMError.USER_ALREADY_EXISTS){
									Toast.makeText(getApplicationContext(), getResources().getString(R.string.User_already_exists), Toast.LENGTH_SHORT).show();
								}else if(errorCode == EMError.UNAUTHORIZED){
									Toast.makeText(getApplicationContext(), getResources().getString(R.string.registration_failed_without_permission), Toast.LENGTH_SHORT).show();
								}else if(errorCode == EMError.ILLEGAL_USER_NAME){
								    Toast.makeText(getApplicationContext(), getResources().getString(R.string.illegal_user_name),Toast.LENGTH_SHORT).show();
								}else{
									Toast.makeText(getApplicationContext(), getResources().getString(R.string.Registration_failed) + e.getMessage(), Toast.LENGTH_SHORT).show();
								}
							}
						});
					}
				}
			}).start(); 
            */
		}
	}
	/**
	 * 注册成功后手机号码传到登录页面
	 */
	public void back() {

		Intent intent = new Intent();
		 intent.setClassName( getApplicationContext(), "com.findu.activity.LoginActivity" );
		
		intent.putExtra("data_return", mRegister_edt_name.getText().toString().trim());
				
		/*setResult(RESULT_OK, intent);
		Log.d("back", "传值到登录页面");*/
		
		
		//不需要接收组件的返回值，就可以直接这样激活了
		 //startActivity(intent); 
	    //需要接收返回结果。注意返回的结果码
	    startActivityForResult(intent, 100);
	    finish();

	}
	/**
	 * 添加数据到 验证页面
	 */
	public void  back2() {
		Bundle bundle = new Bundle();

		bundle.putString("username", mRegister_edt_name.getText().toString().trim());
		bundle.putString("pwd", mRegister_edt_pwd.getText().toString().trim());

		Intent intent = new Intent();
		//第二个参数是要跳转的页面的全路径  
        //intent.setClassName( RegisterActivity.this, "com.findu.activity.SecurityCodeActivity" );
        intent.setClassName( getApplicationContext(), "com.findu.activity.SecurityCodeActivity" );
		intent.putExtras(bundle);
		//setResult(RESULT_OK, intent);
		 //不需要接收组件的返回值，就可以直接这样激活了
		  startActivity(intent);  
		  
		    //需要接收返回结果。注意返回的结果码
		    //startActivityForResult(intent, 100);
		  
		  finish(); 
		// 关闭当前页面  
        // System.exit(0);  
         //无论是exit还是finish都是可以的  
         //SendActivity.this.finish();  
		 
	}
	
	
	/**
	 * CIA验证手机
	 */
    public 	void verification(String phoneNumber){

        // TODO 判断网络状态

        // TODO 校验手机号码格式

         showProgress();
         

        // 调用CIAService发起验证请求
        CIAService.startVerification(phoneNumber, new VerificationListener() {
            /**
             * 校验结果回调
             * @param status        验证状态码
             * @param msg           验证状态的描述
             * @param transId       当前验证请求的流水号，服务器可以根据流水号查询验证的状态
             */
            @Override
            public void onStateChange(int status, String msg, String transId) {
                dismissProgress();

                /**
                 * status 是返回的状态码，CIAService包含了一些常量
                 * @see CIAService.VERIFICATION_SUCCESS 验证成功
                 * @see CIAService.VERIFICATION_FAIL 验证失败，请查看 msg 参数描述，例如手机号码格式错误，手机号格式一般需要开发者先校验
                 * @see CIAService.SECURITY_CODE_MODE   验证码模式
                 *      验证码模式：需要提示用户输入验证码，调用
                 *      @see CIAService.getSecurityCode()    获取当前的验证码，格式类似05311234****，需要提示用户****部分是输入的验证码内容
                 * @see CIAService.REQUEST_EXCEPTION    发生异常，msg 是异常描述，例如没有网络连接，网络连接状况一般需要开发者先判断
                 *
                 * 其他情况，status不在上述常量中，是服务器返回的错误，查看 msg 描述，例如 appId 和 authKey 错误。
                 */
                  Log.d("status", status+"");
                  Log.d("提交到环信", username+"======"+pwd+"本机验证通过提交到环信");
                switch (status) {
				// 本机验证成功
				case CIAService.VERIFICATION_SUCCESS:
					//##############################################
					 //showToast("本机验证成功*_*成功可以不用提示");
					new Thread(new Runnable() {
						public void run() {
							try {

								// 注册到环信 :调用sdk注册方法
								EMChatManager.getInstance().createAccountOnServer(username, pwd);
										
								Log.d("提交到环信1", username + "======" + pwd);
								runOnUiThread(new Runnable() {
									public void run() {
										if (!RegisterActivity.this.isFinishing())
												
											// pd.dismiss();
											progressDialog.dismiss();
										// TODO 保存用户名,注册成功后跳转到登录页面
										// DemoHelper.getInstance().setCurrentUserName(username);
										// PreferenceManager.getInstance().setCurrentUserName(username);
										// Toast.makeText(getApplicationContext(),
										// getResources().getString(R.string.Registered_successfully),
										// 0).show();
										Toast.makeText(RegisterActivity.this,getResources().getString(R.string.Registered_successfully),0).show();

										// 本机--注册成功把值传给登录页面
										back();
									
										// 关闭,调到登录页面
										// startActivity(new Intent(getApplicationContext(),LoginActivity.class));
										
										/*LoginActivity.start(RegisterActivity.this);
										finish();	*/	
									}
								});
							} catch (final EaseMobException e) {
        						runOnUiThread(new Runnable() {
        							public void run() {
        								if (!RegisterActivity.this.isFinishing())
        									//pd.dismiss();
        									progressDialog.dismiss();
        								int errorCode=e.getErrorCode();
        								if(errorCode==EMError.NONETWORK_ERROR){
        									Toast.makeText(getApplicationContext(), getResources().getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
        								}else if(errorCode == EMError.USER_ALREADY_EXISTS){
        									//用户存在
        									Toast.makeText(getApplicationContext(), getResources().getString(R.string.User_already_exists), Toast.LENGTH_SHORT).show();
        									//调到注册页面 ,用户存在就做当前页面即可
        									 //startActivity(new Intent(getApplicationContext(), RegisterActivity.class));
        									//关闭当前页面
        									
        								}else if(errorCode == EMError.UNAUTHORIZED){
        									Toast.makeText(getApplicationContext(), getResources().getString(R.string.registration_failed_without_permission), Toast.LENGTH_SHORT).show();
        								}else if(errorCode == EMError.ILLEGAL_USER_NAME){
        								    Toast.makeText(getApplicationContext(), getResources().getString(R.string.illegal_user_name),Toast.LENGTH_SHORT).show();
        								}else{
        									Toast.makeText(getApplicationContext(), getResources().getString(R.string.Registration_failed) + e.getMessage(), Toast.LENGTH_SHORT).show();
        								}
        							}
        						});
        					}
        				}
        			}).start(); 
                        
                        
                        break;
                      //##############################################
                      //不是本机进行下一步验证
                    case CIAService.SECURITY_CODE_MODE:   
                      //值传给验证码页面
                      //startActivity(new Intent(getApplicationContext(), SecurityCodeActivity.class));
                    	 back2();
                     
                    
                    	 
                         //finish();
                        break;
                        
                    case CIAService.VERIFICATION_FAIL:
                        showToast("验证失败：" + msg);
                        break;
                    case CIAService.REQUEST_EXCEPTION:
                        showToast("请求异常：" + msg);
                        break;
                    default:
                        // 服务器返回的错误
                        showToast(msg);
                }
            }
        });
    
		
	}
	
	 /**
     * 显示进度条对话框
     */
    private void showProgress(){
        dismissProgress();
        progressDialog = ProgressDialog.show(RegisterActivity.this, "正在验证", "请稍后...");
    }

    /**
     * 关闭进度条对话框
     */
    private void dismissProgress(){
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
    /**
     * Toast提示
     *
     * @param txt
     */
    private void showToast(String txt) {

        Toast.makeText(RegisterActivity.this, txt, Toast.LENGTH_LONG).show();
    }
    
}

  
	
	
 
